const Koa = require("koa");
const KoaRouter = require("@koa/router");
const multer = require("@koa/multer"); // koa的文件上传中间件

const app = new Koa(); // 创建app对象

// const upload = multer({
//   dest: "./uploads", // 指定文件上传的目录
// })

const upload = multer({
  storage: multer.diskStorage({
    destination(req, file, cb) {
      cb(null, "./uploads");
    },
    filename(req, file, cb) {
      cb(null, Date.now() + "-" + file.originalname);
    },
  }),
});

const uploadRouter = new KoaRouter({ prefix: "/upload" }); // 创建路由对象

uploadRouter.post("/avatar", upload.single("avatar"), (ctx, next) => {
  console.log(ctx.req.file);
  ctx.body = "上传成功";
});

uploadRouter.post("/photos", upload.array("photos"), (ctx, next) => {
  console.log(ctx.req.files);
  ctx.body = "上传成功";
});

app.use(uploadRouter.routes());
app.use(uploadRouter.allowedMethods());

app.listen(6000, () => {
  console.log("服务器启动成功");
});
